package com.xkdx.guangguang.fragment.blog;

import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.FragmentManager;
import android.text.SpannableString;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.weibo.sdk.android.Oauth2AccessToken;
import com.weibo.sdk.android.WeiboException;
import com.weibo.sdk.android.api.FriendShipGroupAPI;
import com.weibo.sdk.android.net.RequestListener;
import com.xkdx.caipiao.R;
import com.xkdx.guangguang.fragment.BaseFragment;
import com.xkdx.guangguang.module.cache.XkCache;
import com.xkdx.guangguang.module.network.AbsModule;
import com.xkdx.guangguang.shareclass.SinaGroup;
import com.xkdx.guangguang.shareclass.User;
import com.xkdx.guangguang.util.IOUtils;
import com.xkdx.guangguang.util.SinaWeiboUtils;
import com.xkdx.guangguang.wiget.XListView;
import com.xkdx.guangguang.wiget.XListView.IXListViewListener;

public class BlogFragment extends BaseFragment implements IXListViewListener {
	private final static String TAG = "BlogFragment";
	private XListView listView;
	private Button back;
	private View loadMoreView;
	private Button load;
	private MyAdapter adpter;
	// ProgressBar pb;
	private Button refresh;
	private String tag;
	private long groupID;
	private String token;

	// 新浪微博参数
	private int page = 1;
	private int count = 10;
	private long max_id = 0;

	private List<SinaGroup> groupInfos;
	private int Tag = 0;
	private List<SinaGroup> infos;

	private ImageLoader imageLoader = ImageLoader.getInstance();
	private DisplayImageOptions options;
	private String msKey;
	private int mCacheEffective = 360;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		groupInfos = new ArrayList<SinaGroup>();
		infos = new ArrayList<SinaGroup>();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		View view = inflater.inflate(R.layout.weibo, container, false);
		// pb=(ProgressBar)view.findViewById(R.id.blog_progressbar);
		TextView title = (TextView) view.findViewById(R.id.text_login);
		tag = getArguments().getString("tag");
		groupID = getArguments().getLong("groupID"); // 分组id
		token = getArguments().getString("token");

		// Log.i("token", token);
		if (tag.equals("商场")) {
			title.setText("商场微博");
			msKey = "shop";
		} else if (tag.equals("奢侈品")) {
			title.setText("奢侈品微博");
			msKey = "luxury";
		} else if (tag.equals("腕表")) {
			title.setText("腕表微博");
			msKey = "watch";
		} else if (tag.equals("美食")) {
			title.setText("美食微博");
			msKey = "food";
		} else if (tag.equals("信用卡")) {
			title.setText("信用卡微博");
			msKey = "creditcard";
		} else if (tag.equals("服饰")) {
			title.setText("服饰微博");
			msKey = "dress";
		} else if (tag.equals("化妆品")) {
			title.setText("化妆品微博");
			msKey = "toiletries";
		} else if (tag.equals("名人明星")) {
			title.setText("名人明星微博");
			msKey = "star";
		} else if (tag.equals("数码家居")) {
			title.setText("数码家居微博");
			msKey = "digital";
		}

		listView = (XListView) view.findViewById(R.id.listView);

		// progressbar = (ProgressBar) view.findViewById(R.id.weibo_pb);
		// listView.setDivider(null);
		listView.setPullLoadEnable(true);
		listView.setXListViewListener(this);

		back = (Button) view.findViewById(R.id.registe_back);
		refresh = (Button) view.findViewById(R.id.refresh);

		dataLoadDialog.setOnCancelListener(new OnCancelListener() {
			@Override
			public void onCancel(DialogInterface dialog) {
				getFragmentManager().popBackStack();
			}
		});

		back.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				FragmentManager fm = getFragmentManager();
				fm.popBackStack();

			}
		});
		refresh.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				onRefresh();
			}
		});

		// new Thread() {
		// public void run() {
		// RequsetGroupInfo(page, count, max_id, Tag); // 获取分组信息
		// };
		// }.start();

		InputStream in = XkCache.getBizDataCache(msKey, mCacheEffective);
		if (in != null) {
			String json = "";
			try {
				json = IOUtils.forInputStreamToString(in);
				groupInfos = Parjson(json);
				adpter = new MyAdapter(getActivity(), listView, groupInfos);
				listView.setAdapter(adpter);

			} catch (Exception e) {
				e.printStackTrace();
			}

		} else {
			dataLoadDialog.show();

			RequsetGroupInfo(page, count, max_id, Tag); // 获取分组信息
		}
		options = new DisplayImageOptions.Builder()
				.showStubImage(R.drawable.defaultweibo)
				.showImageForEmptyUri(R.drawable.defaultweibo)
				.showImageOnFail(R.drawable.defaultweibo)
				.resetViewBeforeLoading().cacheOnDisc()
				.imageScaleType(ImageScaleType.EXACTLY)
				.bitmapConfig(Bitmap.Config.RGB_565).build();

		return view;
	}

	private Handler h = new Handler() {

		public void handleMessage(android.os.Message msg) {
			if (getActivity() == null) {
				return;
			}

			if (msg.what == 1) {
				groupInfos = infos;
				// Log.i("ok",msKey);
				adpter = new MyAdapter(getActivity(), listView, groupInfos);
				listView.setAdapter(adpter);
				// pb.setVisibility(View.GONE);
				if (dataLoadDialog != null && dataLoadDialog.isShowing()) {
					dataLoadDialog.dismiss();
				}

			}
			if (msg.what == 2) {
				if (dataLoadDialog != null && dataLoadDialog.isShowing()) {
					dataLoadDialog.dismiss();
				}
				Toast.makeText(getActivity(), "没有数据", Toast.LENGTH_SHORT)
						.show();

			}

			if (msg.what == 3) {
				groupInfos = infos;
				adpter = new MyAdapter(getActivity(), listView, groupInfos);
				listView.setAdapter(adpter);
				onLoad();
				if (dataLoadDialog != null && dataLoadDialog.isShowing()) {
					dataLoadDialog.dismiss();
				}
			}
			if (msg.what == 4) {
				// XkCache.addBizCache(msKey, groupInfos.toString().getBytes());
				for (int k = 0; k < infos.size(); k++) {
					groupInfos.add(infos.get(k));
				}
				adpter.notifyDataSetChanged();
				listView.setSelection((page - 1) * 10);
				onLoad();
				if (dataLoadDialog != null && dataLoadDialog.isShowing()) {
					dataLoadDialog.dismiss();
				}
			}

		};
	};

	private void onLoad() {
		listView.stopRefresh();
		listView.stopLoadMore();
		listView.setRefreshTime(getCurrentTime());
	}

	class MyAdapter extends BaseAdapter {
		ListView listView;
		// private ImageLoader imageLoader;
		List<SinaGroup> groupList;

		public MyAdapter(Activity activity, ListView listView,
				List<SinaGroup> groupList) {
			super();
			this.listView = listView;
			// imageLoader = ImageLoader.getInstance(getActivity());
			this.groupList = groupList;

		}

		public View getView(final int position, View convertView,
				ViewGroup parent) {
			Activity activity = getActivity();

			final ViewHolder holder;
			if (convertView == null) {
				LayoutInflater inflater = activity.getLayoutInflater();
				convertView = inflater.inflate(R.layout.weibo_item, null);
				holder = new ViewHolder();
				holder.imageView = (ImageView) convertView
						.findViewById(R.id.item_image);
				holder.titleImage = (ImageView) convertView
						.findViewById(R.id.head);
				holder.textView = (TextView) convertView
						.findViewById(R.id.name);
				holder.time = (TextView) convertView.findViewById(R.id.time);

				holder.weiboContent = (TextView) convertView
						.findViewById(R.id.weibotext);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}

			final String imageUrl = groupList.get(position).getThumbnail_pic();
			String text = groupList.get(position).getText();

			String titleImageUrl = "";
			String creen_name = "";
			User user = groupList.get(position).getUser();
			if (user != null) {
				titleImageUrl = user.getProfile_image_url();
				creen_name = user.getScreen_name();
			}
			String time = getTime(groupList.get(position).getCreated_at());
			holder.imageView.setImageResource(R.drawable.defaultweibo);
			if (imageUrl == null || ("".equals(imageUrl))) {
				holder.imageView.setVisibility(View.GONE);
			} else {
				holder.imageView.setVisibility(View.VISIBLE);
				// imageLoader.addTask(imageUrl, holder.imageView);
				imageLoader.displayImage(imageUrl, holder.imageView, options);
			}

			holder.titleImage.setImageResource(R.drawable.defaultweibo);
			if (titleImageUrl == null || "".equals(titleImageUrl)) {
			} else {
				// imageLoader.addTask(titleImageUrl, holder.titleImage);
				imageLoader.displayImage(titleImageUrl, holder.titleImage,
						options);
			}

			SpannableString spann = SinaWeiboUtils.formatContentNoClick(text);
			holder.weiboContent.setText(spann);

			holder.textView.setText(creen_name + " ");
			holder.time.setText(time);
			holder.imageView.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// String Bmiddle =
					// groupList.get(position).getBmiddle_pic();
					String origle = groupList.get(position).getOriginal_pic();
					Intent intent = new Intent(getActivity(),
							ShowLargeMap.class);

					if ("".equals(origle) || origle == null) {
						if (imageUrl != null && "".equals(imageUrl)) {
							intent.putExtra("origeMap", imageUrl);
							intent.putExtra("thumb", imageUrl);
						}
					} else {
						intent.putExtra("origeMap", origle);
						intent.putExtra("thumb", imageUrl);
					}

					if (!("".equals(imageUrl)) && imageUrl != null) {

						startActivity(intent);

						getActivity().overridePendingTransition(
								R.anim.main_enter, R.anim.main_exit);
					} else {
						Toast.makeText(getActivity(), "没有相关的大图查看...",
								Toast.LENGTH_SHORT).show();
					}
				}
			});
			return convertView;
		}

		@Override
		public int getCount() {

			return groupList.size();
		}

		@Override
		public Object getItem(int position) {
			return groupList.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

	}

	class ViewHolder {
		private TextView textView, weiboContent, time;
		private ImageView imageView, titleImage;
	}

	private String getCurrentTime() {
		SimpleDateFormat format = new SimpleDateFormat("MM-dd hh:mm");
		Date date = new Date(System.currentTimeMillis());
		return format.format(date);
	}

	// 根据sina账号token获取分组信息
	// "2.00hBHaUDGw3u_Bb2f0d3f89cnDoryC"
	private void RequsetGroupInfo(int page, int count, long max_id2,
			final int tag) {
		Oauth2AccessToken oauth2AccessToken = new Oauth2AccessToken(token,
				"157313922");
		FriendShipGroupAPI frindship = new FriendShipGroupAPI(oauth2AccessToken);
		// Log.i("微博","groupID:"+groupID+",token:"+token+",page:"+page+",count:"+count+",max_id2:"+max_id2);
		frindship.getIDS(groupID, token, page, count, max_id2,
				new RequestListener() {

					@Override
					public void onIOException(IOException e) {
					}

					@Override
					public void onError(WeiboException e) {

						if (dataLoadDialog != null
								&& dataLoadDialog.isShowing()) {
							dataLoadDialog.dismiss();
						}
					}

					@Override
					public void onComplete(final String response) {

						new Thread() {
							public void run() {
								synchronized (BlogFragment.this) {

									infos = Parjson(response);
									// Log.i("infos", infos.size() + "");
									if (infos.size() != 0 && infos != null) {
										if (tag == 0) {
											XkCache.addBizCache(msKey,
													response.getBytes());
											h.sendEmptyMessage(1);
										} else if (tag == 3) {
											XkCache.addBizCache(msKey,
													response.getBytes());
											h.sendEmptyMessage(3);
										} else if (tag == 4) {
											h.sendEmptyMessage(4);
										}
									} else {
										h.sendEmptyMessage(2);
									}
								}
							};
						}.start();
					}
				});
	}

	// fastJson解析
	private List<SinaGroup> Parjson(String response) {
		List<SinaGroup> list = new ArrayList<SinaGroup>();
		try {
			JSONObject fastObj = (JSONObject) JSON.parseObject(response);

			JSONArray ListGroupInfo = fastObj.getJSONArray("statuses");
			List<SinaGroup> listGroupInfo = JSON.parseArray(
					ListGroupInfo.toString(), SinaGroup.class);
			int i = 0;
			if (listGroupInfo != null && listGroupInfo.size() > 0) {
				for (SinaGroup sg : listGroupInfo) {

					SinaGroup sinaGroup = new SinaGroup();

					sinaGroup.setText(sg.getText());
					sinaGroup.setId(sg.getId());

					if (i == ListGroupInfo.size() - 1) {
						max_id = sinaGroup.getId();
					}

					i++;
					sinaGroup.setCreated_at(sg.getCreated_at());

					User sinaGroupUser = new User();

					if (sg.getUser() != null) {
						sinaGroupUser.setScreen_name(sg.getUser()
								.getScreen_name());
						sinaGroupUser.setProfile_image_url(sg.getUser()
								.getProfile_image_url());
						sinaGroup.setUser(sinaGroupUser);
					}
					if (sg.getThumbnail_pic() != null) {
						sinaGroup.setThumbnail_pic(sg.getThumbnail_pic());
					}
					if (sg.getOriginal_pic() != null) {
						sinaGroup.setOriginal_pic(sg.getOriginal_pic());
					}
					list.add(sinaGroup);
				}
			}
			// Log.i("size", list.size() + "");
		} catch (Exception e) {
			e.getMessage();
			if (dataLoadDialog != null && dataLoadDialog.isShowing()) {
				dataLoadDialog.dismiss();
			}
		}
		return list;
	}

	public String getTime(String str) {
		SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日  HH:mm");

		Long date = Date.parse(str);
		return format.format(new Date(date));

	}

	@Override
	public void onLoadMore() {
		loadMoreData();
	}

	private void loadMoreData() {
		Tag = 4;
		page += 1;
		RequsetGroupInfo(page, count, max_id - 1, Tag); // -1是为了去掉重复项：sina微博文档max_id
														// false int64 //
														// 若指定此参数，则返回ID小于或等于max_id的微博，默认为0。
	}

	@Override
	public void onRefresh() {
		dataLoadDialog.show();
		page = 1;
		max_id = 0;
		downRefresh();
	}

	private void downRefresh() {
		Tag = 3;
		RequsetGroupInfo(page, count, max_id, Tag);

	}

	@Override
	public void findView() {
		// TODO Auto-generated method stub

	}

	@Override
	public void setOnClick() {

	}

	@Override
	public void showLoading() {

	}

	@Override
	public void showLoaded(HashMap<String, AbsModule> map) {

	}

	@Override
	public void showClick(HashMap<String, AbsModule> map) {

	}

	@Override
	public void showLoadMore(HashMap<String, AbsModule> map) {

	}

}
